package java6681.gui;

import java6681.dao.Student6681;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;


public class Dialog6681Controller {

    @FXML
    private AnchorPane root;

    @FXML
    private TextField tfSno;

    @FXML
    private TextField tfSname;

    @FXML
    private TextField tfLx1;

    @FXML
    private TextField tfLx2;

    @FXML
    private Button btnYes;

    private Student6681 student;

    public Student6681 getStudent() { return student; }

    public void initAdd6681(){
        ((Stage) root.getScene().getWindow()).setTitle("添加新学生");
    }

    public void initChange6681(Student6681 student){
        this.student = student;
        ((Stage) root.getScene().getWindow()).setTitle("修改学生信息");
        setValue();
    }

    @FXML
    void no(ActionEvent event) {
        EditStudent6681Controller.isYes = false;
        ((Stage) root.getScene().getWindow()).close();
    }

    @FXML
    void yes(ActionEvent event) {
        String sno = tfSno.getText().trim();
        String sname = tfSname.getText().trim();
        String lx1 = tfLx1.getText().trim();
        String lx2 = tfLx2.getText().trim();
        if(!isValid(sno, sname, lx1, lx2)){
            return;
        }
        if(student == null){
            student = new Student6681(sname,Integer.parseInt(lx1),Integer.parseInt(lx2),sno);
        }else{
            student.setSno(sno);
            student.setSname(sname);
            student.setLx1(Integer.parseInt(lx1));
            student.setLx2(Integer.parseInt(lx2));
        }
        EditStudent6681Controller.isYes = true;
        ((Stage) root.getScene().getWindow()).close();
    }

    void setValue(){
        tfSno.setText(student.getSno());
        tfSname.setText(student.getSname());
        tfLx1.setText(String.valueOf(student.getLx1()));
        tfLx2.setText(String.valueOf(student.getLx2()));
    }

    boolean isValid(String sno, String sname, String lx1, String lx2){
        if("".equals(sno)){
            EditStudent6681Controller.showAlert("学号不能为空!", Alert.AlertType.WARNING, null);
            return false;
        }
        if("".equals(sname)){
            EditStudent6681Controller.showAlert("姓名不能为空!", Alert.AlertType.WARNING, null);
            return false;
        }
        if(!lx1.matches("[0-9]+") || !lx2.matches("[0-9]+")){
            EditStudent6681Controller.showAlert("分数值必须为数字!", Alert.AlertType.WARNING, null);
            return false;
        }
        return true;
    }

}